package com.umgsai.wx.backend.test.opencv;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class BinaryImageParser {

    public static int[][] parseImageToBinaryArray(String imagePath, int rows, int cols) {
        Mat image = Imgcodecs.imread(imagePath, Imgcodecs.IMREAD_GRAYSCALE);

        int[][] binaryArray = new int[rows][cols];

        int cellWidth = image.cols() / cols;
        int cellHeight = image.rows() / rows;

        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                int startX = col * cellWidth;
                int startY = row * cellHeight;
                int endX = startX + cellWidth;
                int endY = startY + cellHeight;

                int whiteCount = 0;
                int blackCount = 0;

                for (int y = startY; y < endY; y++) {
                    for (int x = startX; x < endX; x++) {
                        double pixelValue = image.get(y, x)[0];
                        if (pixelValue == 255) {
                            whiteCount++;
                        } else {
                            blackCount++;
                        }
                    }
                }

                // 判断该区域内白色点和黑色点的数量来确定二进制值
                binaryArray[row][col] = (whiteCount > blackCount) ? 1 : 0;
            }
        }

        return binaryArray;
    }

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        // 图片路径
        String imagePath = "D:\binary_image_multiline_dots.png"; // 替换为你的图片路径

        // 期望的行数和列数
        int rows = 10;
        int cols = 27;

        // 解析图像得到二进制数组
        int[][] binaryArray = parseImageToBinaryArray(imagePath, rows, cols);

        // 打印二进制数组
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                System.out.print(binaryArray[row][col]);
            }
            System.out.println();
        }
    }
}
